<template>
	<eui-page-frame topHeight="66" :bottomHeight="0">
		<template #top>
			<view class="content-img">
				<eui-nav-bar title="公文详情" color="#000000" rightIcon="" />
			</view>
		</template>
		<eui-page-content>
			<eui-base-card :title="info.c_id">
				<eui-detail-show :items="dataItems" v-model="info" size="normal" labelWidth="50px"></eui-detail-show>
			</eui-base-card>
			<eui-base-card title="发文情况">
				<eui-detail-show :items="dataDetail" v-model="info" size="normal" labelWidth="50px"></eui-detail-show>
			</eui-base-card>
			<eui-base-card title="公文文件">
				<view class="right flex-column-between">
					<view :style="{cursor: 'pointer',width:(scrollWidth-24)+'px'}"
						class="text-ellipsis sub_title flex_1 theme-color" :class="[theme]"
						@click="handleFileAction(info.c_doc_name,info.c_id)">
						<image :src="info.c_docimg_url" style="width: 20px;height: 20px;float: left;margin-right: 5px;">
						</image>
						{{info.c_doc_name}}</view>
				</view>
			</eui-base-card>
			<eui-base-card title="录入与审核">
				<eui-detail-show :items="dataInsert" v-model="info" size="normal" labelWidth="25px"></eui-detail-show>
			</eui-base-card>

		</eui-page-content>

	</eui-page-frame>
</template>
<script setup type="ts">
	import { onLoad,onReady } from '@dcloudio/uni-app';
	import { ref } from 'vue';
	import Enjoy from '@/common/enjoy';
	import service from '@/common/service';
	import { useMainStore } from '@/store/modules/store';
	import { useLoginStore } from '@/store/modules/useLoginStore';
	import Guid from '@/common/guid';
	import dateRangUtil from '@/common/dateRangUtil';
	import eventBus from '@/pages/MainViews/eventBus';
	const mainStore = useMainStore();
	const LoginStore = useLoginStore();
	
	import { storeToRefs } from 'pinia';
	import { useThemeStore } from '@/store/themeStore';
	const themeStore = useThemeStore(); // 主题
	const { theme } = storeToRefs(themeStore);
	
	const scrollWidth = ref(uni.getSystemInfoSync().windowWidth-20);
	const scrollHeight = ref((uni.getSystemInfoSync().windowHeight - uni.getSystemInfoSync().statusBarHeight-114) + 'px');
	const statusBarHeight = ref(uni.getSystemInfoSync().statusBarHeight);
	const info = ref({});
	const accessoryList = ref([]);
	const onTapLeft = () =>{
		uni.navigateBack();
	}
	const dataItems = [
	{
			label: "标题",
			prop: "c_doc_title",
			type: "text",
			element: {
			},
		},
		{
			label: "公文号",
			prop: "c_doc_no",
			type: "text",
			colSpan: 12,
			element: {
			},
		},
		{
			label: "公文类型",
			prop: "c_doc_type",
			type: "text",
			colSpan: 12,
			element: {
			},
		},
		{
			label: "拟稿人",
			prop: "c_drafter",
			type: "text",
			colSpan: 12,
			element: {
			},
		},
		{
			label: "拟稿日期",
			prop: "c_create_dt",
			type: "text",
			colSpan: 12,
			element: {
				mode: "YYYY-MM-DD",
			},
		}
	]
	const dataDetail = [
		{
			label: "保密类型",
			prop: "c_doc_conf",
			type: "text",
			colSpan: 12,
			element: {
			},
		},
		{
			label: "紧急程度",
			prop: "c_doc_level",
			type: "text",
			colSpan: 12,
			element: {
			},
		},
		{
			label: "发文部门",
			prop: "c_send_depart",
			type: "text",
			element: {
			},
		}
	]
	const dataInsert=[
		{
			label: "录入",
			prop: "c_drafter",
			type: "text",
			colSpan: 12,
			element: {
			},
		},
		{
			label: "",
			prop: "c_create_dt",
			type: "text",
			colSpan: 12,
			element: {
				mode: "YYYY-MM-DD HH:mm:ss",
			},
		},
		{
			label: "审核",
			prop: "c_au_user",
			type: "text",
			colSpan: 12,
			element: {
			},
		},
		{
			label: "",
			prop: "c_au_dt",
			type: "text",
			colSpan: 12,
			element: {
				mode: "YYYY-MM-DD HH:mm:ss",
			},
		}
	]
	const handleFileAction = (file,fileId) => {
            uni.showModal({
                title: '提示',
                content: `确定要下载文件《${file}》吗?`,
                showCancel: true,
                success: (res) => {
                    if (res.confirm) {
                        console.log('点击了确定，准备下载文件:', file);
                        downloadFile(file,fileId);
                    }
                }
            });
          
    }
	const EnjoyBillQuery = async(BillId,c_id) =>{
		service.enjoyShowLoading('正在加载...');
		let request = {
		    url: LoginStore.EnjoyMain,
		    data: {
		        UniqueKey: "管易通40企业新闻",
		        ObjectData: {
					BillId:BillId
				},
		        MethodName: "GetDocDetail",
		    },
		}
		service.request(request, (res) => {
		    if (res && res.data) {
		        if (!res.data.HasException) {
					const ObjectData = res.data.ObjectData;
					if(ObjectData != null && ObjectData.ds.length > 0) {
						info.value = {
							...ObjectData.ds[0],
							c_drafter:'['+ObjectData.ds[0].c_create_user+']'+ObjectData.ds[0].c_create_user_name,
							c_send_depart: ObjectData.ds[0].c_send_org?'['+ObjectData.ds[0].c_send_org+']'+ObjectData.ds[0].c_send_org_name:'',
							c_au_user:'['+ObjectData.ds[0].c_au_userno+']'+ObjectData.ds[0].c_au_userno_name,
							c_docimg_url: getDocImgType(ObjectData.ds[0].c_doc_name),
						};
					}
					// TODO 接口待优化, 详情未返回阅读状态, 判断是否需要更新已阅状态
					updateInformation(c_id);

		        } else {
		            service.enjoyShowToast(res.data.Exception.Message)
		        }
		    }
			service.enjoyHideLoading();
		}, () => {
			service.enjoyHideLoading();
		    console.log('失败')
		});
	}
	const getDocImgType = docName => {
		let fix = docName.substr(docName.lastIndexOf(".") + 1).toLowerCase();
		if (docName != undefined && docName != "" && fix != undefined) {
			if (fix == 'doc' || fix == 'docx') {
				return '/static/img/knowledge/docx.png';
			} else if (fix == 'txt') {
				return '/static/img/knowledge/txt.png';
			} else if (fix == 'ppt' || fix == 'pptx') {
				return '/static/img/knowledge/pptx.png';
			} else if (fix == 'jpg' || fix == 'png' || fix == 'bmp' || fix == 'jpeg' || fix == 'gif') {
				return '/static/img/knowledge/picture.png';
			} else if (fix == 'exe') {
				return '/static/img/knowledge/exe.png';
			} else if (fix == 'pdf') {
				return '/static/img/knowledge/pdf.png';
			} else if (fix == 'avi' || fix == 'wma' || fix == 'rmvb' || fix == 'mp4' || fix == 'mov' || fix ==
				'mpeg' || fix == 'flv' || fix == 'asf') {
				return '/static/img/knowledge/video.png';
			} else if (fix == 'html' || fix == 'xml') {
				return '/static/img/knowledge/html.png';
			} else if (fix == 'xls' || fix == 'xlsx' || 'xlsm') {
				return '/static/img/knowledge/xml.png';
			} else {
				return '/static/img/knowledge/spl.png';
			}
		} else {
			return '/static/img/knowledge/spl.png';
		}
	}
	const downloadFile=(file,fileId)=>{
      const guid=fileId+'公文';
	  const _url = LoginStore.EnjoyMain.replace('/Enjoy/Service', '');
	  var url = _url + "/File/DownLoadFile/" +
							guid + GetIdTial();
						console.log(url);
						var urlStr = encodeURI(url);
						plus.runtime.openURL(urlStr);
						// if (plus.os.name != "iOS") {
						// 							plus.runtime.openURL(url);
						// 						} else {
						// 							let options = {
						// 								filename: '_downloads/' + file,
						// 								method: 'GET',
						// 							};
						// 							plus.io.resolveLocalFileSystemURL(options.filename,
						// 								function (entry) {
						// 									FileExistsCallback(entry, options, file,
						// 										url);
						// 								},
						// 								function (e) {
						// 									FileNotExistsCallback(e, options, file,
						// 										url);
						// 								}
						// 							);
						// 						}
	}
	//文件已存在
		const FileExistsCallback = (entry, options, filename, guid) => {
			uni.showModal({
				title: '提示',
				content: '选择的文件已下载过,是否直接打开',
				success: function (res) {
					if (res.confirm) {
						// 直接打开
						plus.runtime.openFile(options.filename, function (e) {
							uni.showToast({
								duration: 3500,
								icon: 'none',
								title: "无法打开此文件：" + e.emssage,
								mask: true,
							});
						});
					} else if (res.cancel) { }
				}
			});
		}
		//文件不存在回调函数
		const FileNotExistsCallback = (e, options, filename, c_url) => {
			downLoadFile(options, filename, c_url);
		}
		const downLoadFile = (option, filename, c_url) => {
			let i = 0;
			let updateWatting = plus.nativeUI.showWaiting("正在准备下载文件...");
			let downUrl = c_url;
			let dtask = plus.downloader.createDownload(c_url, option);
			dtask.addEventListener("statechanged", function (task, status) {
				if (!dtask) {
					return;
				}
				switch (task.state) {
					case 1: // 开始
						updateWatting.setTitle("开始下载...");
						break;
					case 2: // 已连接到服务器
						updateWatting.setTitle("链接到服务器...");
						break;
					case 3: // 已接收到数据
						updateWatting.setTitle("已下载:" + task.downloadedSize + "/" + task.totalSize);
						break;
					case 4: // 下载完成
						updateWatting.close();
						uni.showToast({
							duration: 3500,
							icon: 'none',
							title: '下载完成!',
							mask: true,
						});
						plus.runtime.openFile(option.filename, function (e) {
							uni.showToast({
								duration: 3500,
								icon: 'none',
								title: "无法打开此文件：" + e.emssage,
								mask: true,
							});
						});
						break;
				}
			});
			dtask.start();
		}
	// 更新已阅状态
	const updateInformation=c_id=>{
		let request = {
		    url: LoginStore.EnjoyMain,
		    data: {
		        UniqueKey: "管易通40企业新闻",
		        ObjectData: c_id,
		        MethodName: "UpdateMsgReadStatus",
		    },
		}
		service.request(request, (res) => {
		    if (res && res.data) {
		        if (!res.data.HasException) {	
					eventBus.emit('refresh-DocRecList');
					SetCurrentPages();
		        } else {
		            service.enjoyShowToast(res.data.Exception.Message)
		        }
		    }
			service.enjoyHideLoading();
		}, () => {
			service.enjoyHideLoading();
		    console.log('失败')
		});
	}
	// 获取附件
	const GetAccessDoc = c_guid =>{
		let request = {
		    url: LoginStore.EnjoyMain,
		    data: {
		        UniqueKey: "管易通40内部邮件",
		        ObjectData: {
					sBillId:c_guid+'file',
					sBillType: '邮件管理'
				},
		        MethodName: "GetAccessDoc",
		    },
		}
		service.request(request, (res) => {
		    if (res && res.data) {
		        if (!res.data.HasException) {
					const ObjectData = res.data.ObjectData;
					let list = [];
					const Url = LoginStore.EnjoyMain.replace('/Enjoy/Service', '');
					const imgType = ["gif", "jpeg", "jpg", "bmp", "png"];
					for (let i = 0; i < ObjectData.length; i++) {
						let c_type = "";
						if (RegExp("\.(" + imgType.join("|") + ")$", "i").test(ObjectData[i].c_file_name)) {
							c_type = 'img';
						} else {
							c_type = 'file';
						}
						const type_name = c_type == 'img' ? ObjectData[i].c_file_name : ObjectData[i].c_name;
						list.push({
							...ObjectData[i],
							c_filename: ObjectData[i].c_name,
							c_type: c_type,
							c_url: Url + '/File/DownLoadFile/' + ObjectData[i].c_guid + GetIdTial(),
							c_img_sc: Url + '/File/DownLoadFile/' + ObjectData[i].c_guid,
							c_projectName: Url + "/File/DownLoadFile/" + ObjectData[i].c_guid +
								"|" + GetIdTial(),
							c_docimg_url: getDocImgType(type_name == null ? '' :
								type_name),
						})
					}
					accessoryList.value = list;
		        } else {
		            service.enjoyShowToast(res.data.Exception.Message)
		        }
		    }
		}, () => {
		    console.log('失败')
		});
	}
	const GetIdTial = () =>{
		//新服务不需要这块的尾巴了 CT 20241101
		/* const wgtVer = JSON.parse(uni.getStorageSync('MBMAppVerion'));
		let token = JSON.parse(uni.getStorageSync('uniIdToken'));
		if((wgtVer>=110 && wgtVer.length<=5) || wgtVer.length>5){
			// 替换+为-||
			token = token.replace(/\+/g, '-||');
			// 替换/为-|||
			token = token.replace(/\//g, '-|||');
			// 替换=为-||||
			token = token.replace(/=/g, '-||||');
			return "|"+mainStore.loginInfo.sUser+"|"+token;
		}else{
			return "";
		} */
		return '';
	}
	const SetCurrentPages = () =>{
		try {
			let pages = getCurrentPages();
			let prevPage = pages[pages.length - 2];
			prevPage.$vm.$.exposed.onRefresh();
		} catch (e) {
		}
	}
	onLoad(async e=>{
		console.log("e: " + JSON.stringify(e));
		await EnjoyBillQuery(e.id,e.c_id);
	})
</script>

<style lang="scss" scoped>
	@import '@/main.scss';

	.content-img {
		background-color: #FFFFFF;
		background-repeat: no-repeat;
		width: 100%;
	}

	.main-view {
		flex: 1;
		flex-direction: column;
		background-color: #f2f2f2;
		font-size: 14px;
	}

	.font-size-36 {
		font-size: 36rpx;
	}

	.font-size-26 {
		font-size: 26rpx;
	}

	.font-weight-bold {
		font-weight: bold;
	}

	.padding-all-20 {
		padding: 20rpx;
	}

	.padding-all-28 {
		padding: 28rpx;
	}

	.background-color-fff {
		background-color: #fff;
	}

	.border-radius-20 {
		border-radius: 20rpx;
	}

	.flex {
		display: flex;
	}

	.flex-direction-column {
		flex-direction: column !important;
	}

	.text-align-right {
		text-align: right;
	}

	.color-888 {
		color: #888;
	}

	.padding-right-16 {
		padding-right: 16rpx;
	}

	.margin-top-28 {
		margin-top: 28rpx;
	}

	.line-height-1 {
		line-height: 1;
	}

	.margin-top-16 {
		margin-top: 16rpx;
	}

	.padding-bottom-28 {
		padding-bottom: 28rpx;
	}

	.border-bottom-eee {
		border-bottom: solid 1px #eee;
	}

	.attachment-list {
		height: 55px;
		border-radius: 10px;
		background-color: rgba(249, 249, 248, 1);
		margin-bottom: 10px;
		padding: 0 10px;
		font-size: 14px;
	}

	.align-items-center {
		align-items: center;
	}

	.align-items-flex-start {
		align-items: flex-start;
	}

	.justify-content-center {
		justify-content: center;
	}

	.margin-left-30 {
		margin-left: 30rpx;
	}

	.font-size-24 {
		font-size: 24rpx;
	}

	.margin-top-10 {
		margin-top: 10rpx;
	}

	.user-footer {
		position: fixed;
		z-index: 9;
		bottom: 0;
		left: 0;
		right: 0;
		height: 108rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		padding: 0 20rpx;
	}

	.recover-email {
		width: 100rpx;
		height: 68rpx;
		background: linear-gradient(135deg, rgba(2, 183, 230, 1), rgba(54, 169, 243, 1));
		border-radius: 10rpx;
		color: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.recover-input {
		height: 68rpx;
		background-color: rgba(249, 249, 248, 1);
		margin-right: 10px;
		flex: 1;
		display: flex;
		align-items: center;
	}

	.iconfont {
		font-size: 20px;
		width: 40px;
		height: 100%;
		text-align: center;
		line-height: 37px;
		@include themeText("themeText");
	}

	.ellipsis-1 {
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.header-content {
		height: 88rpx;
		padding: 0 6px;
		background-color: #fff;
		align-items: center;
		position: relative;
		z-index: 2;
	}

	.justify-content-space-between {
		justify-content: space-between;
	}

	.justify-content-flex-end {
		justify-content: flex-end;
	}

	.theme-color {
		color: var(--theme-color);
	}
</style>